
"use strict";
const mvc = require('cosjs.mvc');
const mongodb = require('mongodb');
const build = require('../../../share/format/build');
const random = mvc.library.require('random');
/**
 * @name dispatchBuild
 * 派遣
 */

/**
 * @name refreshTask
 * 刷新任务
 */
exports.refreshTask = async function () {
    const BUILDID = mvc.config('base', 'collectBuild_OrdersDistribute').val;
    this.updater.daily.key('buildRefreshTime.' + BUILDID);
    this.updater.role.key('buildingsInfo.' + BUILDID);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + BUILDID);
    let refTime = this.updater.daily.get('buildRefreshTime.' + BUILDID) || 0;
    let taskData;
    if (refTime >= 0) {
        let next = refTime + 1;
        const refCostBaseConfig = mvc.config("dailyGrowthCost", next);
        if (!refCostBaseConfig) {
            return this.quick_error("m2sgrbs1", "配置不存在", "hookCost", next);
        }
        this.updater.item.sub(refCostBaseConfig["orderBuildRefresh"].itemID, refCostBaseConfig["orderBuildRefresh"].cost);
    }
    if (!buildData.level) {
        return this.quick_error('M2saghge150', '建筑等级不存在');
    }
    taskData = rollTaskGroup(buildData.level);
    let taskList = buildData.taskList;
    let taskDataList = {};
    let delNum = 0;
    for (let k in taskList) {
        if (taskList[k].state == 1) {
            continue;
        }
        if (taskList[k].beginTime == 0) {
            continue;
        }
        delNum++;
        taskDataList[k] = taskList[k];
    }
    let buildConfig = mvc.config('dispatchBuild', buildData.level);
    if (!buildConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    const MAX_TASK_NUM = buildConfig.maxOrderNum;
    delNum = MAX_TASK_NUM - delNum;
    for (let k in taskData) {
        taskDataList[k] = taskData[k];
        delNum--;
        if (delNum == 0) {
            break;
        }
    }
    buildData.taskList = taskDataList;
    this.updater.daily.add('buildRefreshTime.' + BUILDID, 1);
    this.updater.role.set('buildingsInfo.' + BUILDID, buildData);
    return this.updater.save();
}





//根据任务组，去ordersBuild表里找到数据，roll出一个随机任务
function rollTaskList(taskGroup) {
    let orderConfig = mvc.config('orderRank', taskGroup);
    if (!orderConfig) {
        return this.quick_error("M2saghge50", "配置不存在", taskGroup);
    }
    let k = random.Relative(orderConfig.Coll, 'val');
    if (k === false) {
        return this.quick_error("M7GHLB123", 'err request', k);
    }
    let taskConfigData = orderConfig.Coll[k];
    let taskID = mongodb.ObjectID().toString();
    //随机出蛋族类型
    let eggList = mvc.config('party');
    //eggList是json对象，随机挑一个出来
    //如果rankPossible的值是1，才能加入到values里
    let values = [];
    for (let k in eggList) {
        if (eggList[k].rankPossible == 1) {
            values.push(eggList[k]);
        }
    }
    let randomValue = values[Math.floor(Math.random() * values.length)];
    let eggType = randomValue.id;
    let taskData = {
        "_id": taskID,
        "id": taskConfigData.orderId,
        "bigSuccess": 0,
        "eggType": eggType,
        "beginTime": 0,
        "state": 0,
        "unitList": [],
    }
    return taskData;
}
/**
 * @name startTask
 * @param string taskID 任务ID
 * @param string unitList 崽崽ID 以","分割
 * 派遣任务
 */
exports.startTask = async function () {
    let taskID = this.get('taskID', 'string');
    let unitTemp = this.get('unitList', 'string');
    if (!taskID || !unitTemp) {
        return this.quick_error("M2saghge50", "参数错误");
    }
    let unitList = unitTemp.split(",");
    for (let s of unitList) {
        if (!s) {
            return this.quick_error('M2saghge150', '崽崽列表不能为空');
        }
        this.updater.item.key(s);
    }
    const BUILDID = mvc.config('base', 'collectBuild_OrdersDistribute').val;
    this.updater.role.key('buildingsInfo.' + BUILDID);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + BUILDID);
    if (!buildData.taskList) {
        return this.quick_error('M2saghge150', '任务列表不存在');
    }
    if (!buildData.taskList[taskID]) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskData = buildData.taskList[taskID];
    //判断任务是否已经开始
    if (taskData.beginTime != 0) {
        return this.quick_error('M2saghge150', '任务已经开始');
    }
    if (taskData.state == 1) {
        return this.quick_error('M2saghge150', '任务已经完成');
    }
    let taskConfig = mvc.config('ordersBuild', taskData.id);
    // let exRewardFlag = 1;
    taskData.bigSuccess = 1;
    //判断是否有角色不存在
    let unitNum = 0;
    for (let k in unitList) {
        let unitData = this.updater.item.get(unitList[k]);
        if (!unitData) {
            return this.quick_error('M2saghge150', '崽崽不存在', unitList[k]);
        }
        unitNum++;
        //去表里读崽崽的蛋族类型
        let unitConfig = mvc.config('unit', unitData.id);
        if (!unitConfig) {
            return this.quick_error('M2saghge150', '配置不存在', unitData.id);
        }
        //判断是否满足蛋族条件
        if (unitConfig.race != taskData.eggType) {
            taskData.bigSuccess = 0;
        }
    }
    //unitNum和unitList的长度比较
    if (unitNum != taskConfig.orderRequiredNum) {
        return this.quick_error('M2saghge150', '崽崽数量不符合');
    }
    //判断是否已经在其他的任务里
    let unitSet = new Set(unitList);
    for (let k in buildData.taskList) {
        if (buildData.taskList[k].unitList) {
            for (let s in buildData.taskList[k].unitList) {
                if (unitSet.has(buildData.taskList[k].unitList[s])) {
                    return this.quick_error('M2saghge150', '崽崽已经在其他任务里', buildData.taskList[k].unitList[s]);
                }
            }
        }
    }
    //设置好任务开始时间和结束时间
    let time = Date.now();
    taskData.beginTime = time;
    taskData.unitList = unitList;
    this.updater.role.set('buildingsInfo.' + BUILDID + ".taskList." + taskID, taskData);
    return this.updater.save();
}


/**
 * @name completeTask
 * @param string taskID 任务ID
 * 完成任务
 */
exports.completeTask = async function () {
    let taskID = this.get('taskID', 'string');
    if (!taskID) {
        return this.quick_error("M2saghge50", "参数错误");
    }
    const BUILDID = mvc.config('base', 'collectBuild_OrdersDistribute').val;
    this.updater.role.key('buildingsInfo.' + BUILDID);
    this.updater.daily.key('completeBuildTask');
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + BUILDID);
    let completeBuildTask = this.updater.daily.get('completeBuildTask') || 0;
    if (!buildData.taskList) {
        return this.quick_error('M2saghge150', '任务列表不存在');
    }
    let buildConfig = mvc.config('dispatchBuild', buildData.level);
    if (!buildConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    if (completeBuildTask >= buildConfig.maxOrderNum) {
        return this.quick_error('M2saghge150', '已到达每日上限');
    }

    this.updater.daily.add("completeBuildTask", 1);
    if (!buildData.taskList[taskID]) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskData = buildData.taskList[taskID];
    if (taskData == {}) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskConfig = mvc.config('ordersBuild', taskData.id);
    if (!taskConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    //判断任务是否已经开始
    if (taskData.beginTime == 0) {
        return this.quick_error('M2saghge150', '任务未开始');
    }
    if (taskData.state == 1) {
        return this.quick_error('M2saghge150', '任务已经完成');
    }
    //判断任务是否已经完成
    if ((taskData.beginTime + buildConfig.orderTime * 60 * 1000) > Date.now()) {
        return this.quick_error('M2saghge150', '任务未完成');
    }
    //设置任务的完成状态
    taskData.state = 1;
    taskData.unitList = [];
    this.updater.role.set('buildingsInfo.' + BUILDID + ".taskList." + taskID, taskData);
    //给任务奖励
    this.updater.add(taskConfig.award, 1);
    if (taskData.bigSuccess) {
        this.updater.add(taskConfig.exAward, 1);
    }
    return this.updater.save();
}

/**
 * @name resetTask
 * @param string taskID 任务ID
 * 取消派遣任务
 */
exports.resetTask = async function () {
    let taskID = this.get('taskID', 'string');
    if (!taskID) {
        return this.quick_error("M2saghge50", "参数错误");
    }
    const BUILDID = mvc.config('base', 'collectBuild_OrdersDistribute').val;
    this.updater.role.key('buildingsInfo.' + BUILDID);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + BUILDID);
    if (!buildData.taskList) {
        return this.quick_error('M2saghge150', '任务列表不存在');
    }
    if (!buildData.taskList[taskID]) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskData = buildData.taskList[taskID];
    if (taskData == {}) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    if (taskData.state == 1) {
        return this.quick_error('M2saghge150', '任务已经完成');
    }
    //判断任务是否已经开始
    if (taskData.beginTime == 0) {
        return this.quick_error('M2saghge150', '任务未开始');
    }
    let buildConfig = mvc.config('dispatchBuild', buildData.level);
    if (!buildConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    //判断任务是否已经完成
    if ((taskData.beginTime + buildConfig.orderTime * 60 * 1000) < Date.now()) {
        return this.quick_error('M2saghge150', '任务已经完成');
    }
    //重置beginTime
    taskData.beginTime = 0;
    //重置unitList  
    taskData.unitList = [];
    this.updater.role.set('buildingsInfo.' + BUILDID + ".taskList." + taskID, taskData);
    return this.updater.save();
}



/**
 * @name oneKeyCompleteTask
 * @param string taskID 任务ID
 * 花钱完成任务
 */
exports.oneKeyCompleteTask = async function () {
    let taskID = this.get('taskID', 'string');
    if (!taskID) {
        return this.quick_error("M2saghge50", "参数错误");
    }
    const BUILDID = mvc.config('base', 'collectBuild_OrdersDistribute').val;
    this.updater.role.key('buildingsInfo.' + BUILDID);
    this.updater.daily.key('completeBuildTask');
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + BUILDID);
    let completeBuildTask = this.updater.daily.get('completeBuildTask') || 0;
    if (!buildData.taskList) {
        return this.quick_error('M2saghge150', '任务列表不存在');
    }
    let buildConfig = mvc.config('dispatchBuild', buildData.level);
    if (!buildConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    if (completeBuildTask >= buildConfig.maxOrderNum) {
        return this.quick_error('M2saghge150', '已到达每日上限');
    }
    this.updater.daily.add("completeBuildTask", 1);
    if (!buildData.taskList[taskID]) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskData = buildData.taskList[taskID];
    if (taskData == {}) {
        return this.quick_error('M2saghge150', '任务不存在');
    }
    let taskConfig = mvc.config('ordersBuild', taskData.id);
    if (!taskConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    //判断任务是否已经开始
    if (taskData.beginTime == 0) {
        return this.quick_error('M2saghge150', '任务未开始');
    }
    if (taskData.state == 1) {
        return this.quick_error('M2saghge150', '任务已经完成');
    }
    //改成花钱完成任务
    this.updater.sub(taskConfig.orderQuickFinish.itemId, taskConfig.orderQuickFinish.num);
    //设置任务的完成状态
    taskData.state = 1;
    taskData.unitList = [];
    this.updater.role.set('buildingsInfo.' + BUILDID + ".taskList." + taskID, taskData);
    //给任务奖励
    this.updater.add(taskConfig.award, 1);
    if (taskData.bigSuccess) {
        this.updater.add(taskConfig.exAward, 1);
    }
    return this.updater.save();
}

exports.rollTask = function (buildLv) {
    return rollTaskGroup(buildLv);
}
function rollTaskGroup(buildLv) {
    let buildConfig = mvc.config('dispatchBuild', buildLv);
    if (!buildConfig) {
        return this.quick_error('M2saghge150', '配置不存在');
    }
    const MAX_TASK_NUM = buildConfig.maxOrderNum;
    let taskList = {};
    for (let i = 0; i < MAX_TASK_NUM; i++) {
        let k = random.Relative(buildConfig.orderAbility, 'val');
        if (k === false) {
            return this.quick_error("M7GHLB123", 'err request', k);
        }
        let taskData = rollTaskList(buildConfig.orderAbility[k].orderId);
        taskList[taskData._id] = taskData;
        // taskList.push(taskData);
    }
    return taskList;
}